package com.learn.aop;

import com.learn.mapper.OperateLogMapper;
import com.learn.pojo.OperateLog;
import com.learn.util.JwtUtil;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

@Slf4j
@Component
@Aspect
public class LogAspect {

    @Autowired
    private HttpServletRequest req;
    @Autowired
    private OperateLogMapper operateLogMapper;
    @Around("@annotation(com.learn.anno.Log)")
    public Object recordLog(ProceedingJoinPoint joinPoint) throws Throwable {


        //记录操作人ID、类名、方法名、时间、参数、返回值、耗时
        String jwt = req.getHeader("token");
        Claims claims = JwtUtil.parseJwt(jwt);
        Integer operateUser = (Integer) claims.get("id");

        String className = joinPoint.getTarget().getClass().getName();

        String methodName = joinPoint.getSignature().getName();

        String methodParams = joinPoint.getArgs().toString();

        Long start = System.currentTimeMillis();

        LocalDateTime operateTime = LocalDateTime.now();

        //执行方法
        Object proceed = joinPoint.proceed();

        Long end = System.currentTimeMillis();

        Long costTime = end - start;

        OperateLog log1 = new OperateLog(null, operateUser, operateTime, className, methodName, methodParams, proceed.toString(), costTime);
        operateLogMapper.insert(log1);
        log.info("记录日志:{}",log1.toString());
        return proceed;
    }
}
